# -*- coding: utf-8 -*-
import os
import sys

import requests
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from apitools import plant, animal, logo


# 另外获取token值 图像识别
P_KEY = 'xxxxxxxxxxxxxxxx'
P_SECRET = 'xxxxxxxxxxxxxxxx'


class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.setFixedSize(800, 700)
        self.horizontalLayoutWidget = QtWidgets.QWidget(Form)
        self.horizontalLayoutWidget.setGeometry(QtCore.QRect(90, 50, 171, 31))
        self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.label = QtWidgets.QLabel(self.horizontalLayoutWidget)
        self.label.setObjectName("label")
        self.horizontalLayout.addWidget(self.label)
        self.comboBox = QtWidgets.QComboBox(self.horizontalLayoutWidget)
        self.comboBox.setObjectName("comboBox")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        # 下拉框的多少一一对应
        # self.comboBox.addItem("")
        #
        self.horizontalLayout.addWidget(self.comboBox)

        self.horizontalLayoutWidget_2 = QtWidgets.QWidget(Form)
        self.horizontalLayoutWidget_2.setGeometry(QtCore.QRect(40, 100, 271, 31))
        self.horizontalLayoutWidget_2.setObjectName("horizontalLayoutWidget_2")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_2)
        self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")

        self.label_2 = QtWidgets.QLabel(self.horizontalLayoutWidget_2)
        self.label_2.setObjectName("label_2")
        self.horizontalLayout_2.addWidget(self.label_2)

        self.lineEdit = QtWidgets.QLineEdit(self.horizontalLayoutWidget_2)
        self.lineEdit.setObjectName("lineEdit")
        self.horizontalLayout_2.addWidget(self.lineEdit)

        self.pushButton = QtWidgets.QPushButton(self.horizontalLayoutWidget_2)
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout_2.addWidget(self.pushButton)
        self.label_3 = QtWidgets.QLabel(Form)
        self.label_3.setGeometry(QtCore.QRect(10, 150, 380, 500))
        # self.label_3.setStyleSheet("background-color: rgb(255, 255, 127);")
        self.label_3.setStyleSheet("border-width: 1px;border-style: solid;boder-color: rgb(0,0,0);")
        self.label_3.setText("")
        self.label_3.setObjectName("label_3")

        # 开始按钮
        self.pushButton_1 = QtWidgets.QPushButton(Form)
        self.pushButton_1.setGeometry(QtCore.QRect(500, 30, 100, 100))
        self.pushButton_1.setObjectName("pushButton_1")

        self.label_4 = QtWidgets.QLabel(Form)
        self.label_4.setGeometry(QtCore.QRect(410, 150, 380, 500))
        # self.label_4.setStyleSheet("background-color: rgb(85, 255, 0);")
        self.label_4.setStyleSheet("border-width: 1px;border-style: solid;boder-color: rgb(0,0,0);")
        self.label_4.setText("")
        self.label_4.setObjectName("label_4")

        # 输出按钮
        self.pushButton_2 = QtWidgets.QPushButton(Form)
        self.pushButton_2.setGeometry(QtCore.QRect(500, 660, 241, 23))
        self.pushButton_2.setObjectName("pushButton_2")

        # clear
        self.pushButton_3 = QtWidgets.QPushButton(Form)
        self.pushButton_3.setGeometry(QtCore.QRect(650, 30, 100, 100))
        self.pushButton_3.setObjectName("pushButton_3")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "图片识别"))
        self.label.setText(_translate("Form", "选择识别类型:"))
        self.comboBox.setItemText(0, _translate("Form", "植物"))
        self.comboBox.setItemText(1, _translate("Form", "动物"))
        self.comboBox.setItemText(2, _translate("Form", "logo"))
        self.comboBox.setItemText(3, _translate("Form", "other"))
        #
        # self.comboBox.setItemText(2, _translate("Form", "其他"))
        #
        self.label_2.setText(_translate("Form", "选择要识别的图片:"))
        self.pushButton.setText(_translate("Form", "选择"))
        self.pushButton_1.setText(_translate("Form", "开始"))
        self.pushButton_2.setText(_translate("Form", "点击导出CSV结果文件"))
        self.pushButton_3.setText(_translate("Form", "clear"))

        # 为选择按钮添加点击事件
        self.pushButton.clicked.connect(self.openfile)
        # 为开始按钮添加API事件
        self.pushButton_1.clicked.connect(self.run)
        # 为输出按钮添加点击事件
        self.pushButton_2.clicked.connect(self.outputText)
        # 为clear按钮添加刷新事件
        self.pushButton_3.clicked.connect(self.refresh)

    # 错误信息提示
    def show_message(self, errmessage):
        msgBox = QMessageBox(QMessageBox.NoIcon, '提示', errmessage)
        msgBox.setIconPixmap(QPixmap("beauty.png"))
        msgBox.exec()

    # 刷新
    def refresh(self):
        self.lineEdit.setText("")
        self.label_3.setPixmap(QPixmap(""))
        self.label_4.setText("")

    # 开始
    def run(self):
        if self.lineEdit.text() != "":
            # 通过百度ai接口来识别特定类别的图片
            if os.path.exists(self.lineEdit.text()):
                self.typeTp()
            else:
                self.show_message("无效图片地址，请检查！！！")
        else:
            self.show_message("请选择需要识别的图片!!!")

    # 打开文件
    def openfile(self):
        self.download_path = QFileDialog.getOpenFileName(self.horizontalLayoutWidget_2, "选择要识别的图片", "/",
                                                         "Image File(*.jpg *.png)")
        if not self.download_path[0].strip():
            pass
        else:
            # print(self.download_path[0])
            # 把图片路径显示
            self.lineEdit.setText(self.download_path[0])
            # 显示选择的图片 自动解析图片
            pixmap = QPixmap(self.download_path[0])
            # 处理图片  规定大小
            scarePixmap = pixmap.scaled(QSize(380, 500), aspectRatioMode=Qt.KeepAspectRatio)
            # 把图片设置到控件里
            self.label_3.setPixmap(scarePixmap)

    # 输出文件
    def outputText(self):
        if self.label_4.text() != "":
            file_name, _ = QFileDialog.getSaveFileName(self.horizontalLayoutWidget_2, "点击导出CSV文件", "",
                                                       "Text Files(*.csv);;All Files(*)")
            print(file_name)
            if file_name:
                with open(file_name, 'w') as f:
                    f.write(self.label_4.text())
                f.close()
                self.show_message("结果已输出到路径：" + file_name + "。" + "建议在下一次开始之前clear当前数据！！！")
        else:
            self.show_message("无识别结果,请重试！！！")

    # 获取识别ID
    def typeTp(self):
        # 植物
        if self.comboBox.currentIndex() == 0:
            # 识别植物
            # self.get_plant(self.img_get_token())
            result, message = plant.get_plant(self.download_path, self.img_get_token())
        # 动物
        elif self.comboBox.currentIndex() == 1:
            # 识别动物
            result, message = animal.get_animal(self.download_path, self.img_get_token())
        elif self.comboBox.currentIndex() == 2:
            # 识别动物
            result, message = logo.get_logo(self.download_path, self.img_get_token())
        else:
            result, message = "当前模块未涉及,详情请联系xxxxxxxxxx", "识别错误"
        self.label_4.setText(result)
        self.show_message(message)

    # 获取token
    def img_get_token(self):
        # client_id 为官网获取的AK， client_secret 为官网获取的SK
        host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + P_KEY + '&client_secret=' + P_SECRET
        response = requests.get(host)
        if response:
            # print(response.json())
            self.access_token = response.json()['access_token']
            return self.access_token


def start_run():
    app = QtWidgets.QApplication(sys.argv)
    mainWindow = QtWidgets.QMainWindow()
    ui = Ui_Form()
    ui.setupUi(mainWindow)
    mainWindow.show()
    sys.exit(app.exec_())
